﻿using System.Numerics;
using System.Text;
using LanqiQAwebapi.Interface;
using LanqiQAwebapi.Models;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.IdentityModel.Tokens;
using StackExchange.Redis;


namespace LanqiQAwebapi.Todo
{
    public class CacheService : ICacheService
        
    {
        private readonly IConnectionMultiplexer _cache;

        private readonly IDatabase _database;
        private readonly LanQiQaDBContext _LanQiQaDBContext;
        public CacheService(IConnectionMultiplexer cache, LanQiQaDBContext __LanQiQaDBContext)
        {
            _cache = cache;
            _LanQiQaDBContext = __LanQiQaDBContext;
               _database = _cache.GetDatabase();
 
        }
        public void AddBlackToken(string uid, string Token)
        {
            //AccessToken拉黑
            string AccessKey=uid+"_"+Token;
            _database.StringSet(AccessKey, Encoding.UTF8.GetBytes(Token),TimeSpan.FromDays(7));


            //RefishToken拉黑
            _database.StringSet(uid, Encoding.UTF8.GetBytes(Token), TimeSpan.FromDays(7));
        }


        /// <summary>
        /// 检查redis 是否存在拉黑token,True为拉黑
        /// </summary>
        /// <param name="uid"></param>
        /// <param name="Token"></param>
        /// <returns></returns>
        public bool CheckTokenIsBlacke(string uid, string Token)
        {
            var AccessKey=uid+"_"+Token;
            RediskeyIs(AccessKey, Token);
            var data =_database.StringGet(AccessKey).ToString();
            if (data.Length > 0 && data != null)
            {
                return false;
            }
            else { 
            return true;
            
            }
            
         
        }
        /// <summary>
        /// 手机验证码缓存
        /// </summary>
        /// <param name="Phone"></param>
        /// <param name="MessageCode"></param>
        public bool AddSendMessage(string Phone,string MessageCode) 
        {
            if (IncrementAndCheckLimit(Phone,5))
            {
                string key = Phone + "_" + GetSendMessageCount(Phone);
             
                _database.StringSet(key, MessageCode, TimeSpan.FromMinutes(3));
                return true;
            }
           return false;

        }
        public string   GetPhoneMessage(string phoneNumber,int count)
        {
            string key = phoneNumber + "_" + GetSendMessageCount(count.ToString());

            return _database.StringGet(key);

        }
        private int GetSendMessageCount(string phoneNumber)
        {
            string counterKey = $"daily_limit:verification_codes:{phoneNumber}";
            // 尝试获取当前计数
            RedisValue currentCount = _database.StringGet(counterKey);
            var count=int.Parse(currentCount.ToString());
            return count;
        }
        /// <summary>
        /// 每一次电话号码当前的一个计数,用户获取指定标识的电话号码code ，每天每个电话号码只能发送五次，每次时间时间间隔三分钟
        /// </summary>
        /// <param name="phoneNumber"></param>
        /// <returns></returns>
        public int PGetSendMessageCount(string phoneNumber)
        {
            string counterKey = $"daily_limit:verification_codes:{phoneNumber}";
            // 尝试获取当前计数
            RedisValue currentCount = _database.StringGet(counterKey);
            var count = int.Parse(currentCount.ToString());
            return count;
        }
        public bool IncrementAndCheckLimit(string phoneNumber, int dailyLimit)
        {
            string counterKey = $"daily_limit:verification_codes:{phoneNumber}";
            // 尝试获取当前计数
            RedisValue currentCount = _database.StringGet(counterKey);
            // 如果计数不存在，将其设置为1，并设置过期时间为一天
            if (currentCount.IsNull)
            {
                _database.StringSet(counterKey, "1",TimeSpan.FromDays(1));
                return true;
            }
            // 将 RedisValue 转换为 long 类型
            long count = Convert.ToInt64(currentCount);
            // 如果计数存在，检查是否小于每日限制
            if (count < dailyLimit)
            {
                _database.StringIncrement(counterKey);
                return true;
            }
            return false;
        }
        public void GetHotquestion(string Input) 
        {

          
        }


        private void RediskeyIs(string key,string value) 
        {
            if (!_database.KeyExists(key))
            {
                _database.StringSet(key, value);
            }
        }
    }
}
